package com.corpgovernment.organization.service;

import com.corpgovernment.api.organization.model.org.response.GetOrgInfoResponseOld;
import com.corpgovernment.api.organization.model.switchinfo.GetAllSwitchResponse;
import com.corpgovernment.api.organization.model.switchinfo.GetPayConfigRequest;
import com.corpgovernment.api.organization.model.switchinfo.GetSwitchListRequest;
import com.corpgovernment.common.enums.PayTypeEnum;
import com.corpgovernment.common.enums.SiteEnum;
import com.corpgovernment.organization.entity.db.MbOrgInfo;
import com.corpgovernment.organization.entity.db.MbOrgPayType;
import com.corpgovernment.organization.enumm.CorpPayTypeEnum;
import com.corpgovernment.organization.enumm.OrgTypeEnum;
import com.corpgovernment.organization.event.OrgInitEvent;
import com.corpgovernment.organization.mapper.MbOrgInfoMapper;
import com.corpgovernment.organization.service.impl.GetAllSwitchService;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @ClassName: CommonService
 * @description: TODO
 * @author: jiang.luo
 * @date: Created in 18:03 2019/12/12
 * @Version: 1.0
 **/

@Service
@Slf4j
public class CommonService {

    @Autowired
    private IOrgPayTypeService orgPayTypeService;
    @Autowired
    private MbOrgInfoMapper mbOrgInfoMapper;
    @Autowired
    private GetAllSwitchService getAllSwitchService;
    @Autowired
    private SyncPayConfigService syncPayConfigService;


    /**
     * 是否开启
     */
    private static final String ENABLE = "1";
    /**
     * 是否开启
     */
    private static final String TYPE_COMPANY = "C";

    public void savePayType(String orgId, String type, List<OrgInitEvent.PayTypeConfigType> payTypeConfigList){
        if (hasPayConfig(payTypeConfigList)){
            syncPayConfigService.importOrganizationConfig(payTypeConfigList);
            return;
        }
        // 有父级组织使用父级组织的支付方式，否则使用默认的支付方式
        if (!hasParentOrganization(orgId)){
            saveAllPubPayType(orgId, type);
            saveAllOwnPayType(orgId);
        }

    }

    /**
     * 保存各种支付方式（因公）
     */
    public void saveAllPubPayType(String orgId, String type) {

        List<MbOrgPayType> lists = Lists.newArrayList();

        String pub = CorpPayTypeEnum.PUB.toString();
        String pPay = PayTypeEnum.PPAY.getType();
        String accnt = PayTypeEnum.ACCNT.getType();
        if (StringUtils.equals(OrgTypeEnum.D.getCode(), type, false)) {
            for (SiteEnum siteEnum : SiteEnum.values()) {
                if (siteEnum == SiteEnum.OTHER) {
                    continue;
                }
                //部门默认因公为空
                lists.add(new MbOrgPayType(orgId, pub, accnt, siteEnum.getCode()));
                //接送机/接送站 因公目前不需要因私
                if (!siteEnum.getCode().equals(SiteEnum.TRAINTRANSFER.getCode()) && !siteEnum.getCode().equals(SiteEnum.AIRPORTTRANSFER.getCode())){
                    lists.add(new MbOrgPayType(orgId, pub, pPay, siteEnum.getCode()));
                }
            }
        } else {
            for (SiteEnum siteEnum : SiteEnum.values()) {
                if (siteEnum == SiteEnum.OTHER) {
                    continue;
                }
                //接送机/接送站 因公目前不需要因私
                if (!siteEnum.getCode().equals(SiteEnum.TRAINTRANSFER.getCode()) && !siteEnum.getCode().equals(SiteEnum.AIRPORTTRANSFER.getCode())){
                    lists.add(new MbOrgPayType(orgId, pub, pPay, siteEnum.getCode()));
                }
                lists.add(new MbOrgPayType(orgId, pub, accnt, siteEnum.getCode()));
            }
        }
        orgPayTypeService.batchSavePayType(lists);
    }

    /**
     * 保存各种支付方式（因私）
     */
    public void saveAllOwnPayType(String orgId) {
        List<MbOrgPayType> lists = Lists.newArrayList();
        String own = CorpPayTypeEnum.OWN.toString();
        String pPay = PayTypeEnum.PPAY.getType();
        for (SiteEnum siteEnum : SiteEnum.values()) {
            if (siteEnum == SiteEnum.OTHER) {
                continue;
            }
            //部门默认因公为空
            lists.add(new MbOrgPayType(orgId, own, pPay, siteEnum.getCode()));
        }
        orgPayTypeService.batchSavePayType(lists);
    }

    public List<GetOrgInfoResponseOld.OrgPayType> returnData(List<MbOrgPayType> payList, List<GetOrgInfoResponseOld.OrgPayType> payTypeList, String orgId) {
        List<GetOrgInfoResponseOld.OrgPayType> orgPayTypeList = Lists.newArrayList();
        if (CollectionUtils.isEmpty(payList)) {
            return orgPayTypeList;
        }

        payTypeList = payList.stream()
                .filter(p -> p != null && !StringUtils.isEmpty(p.getCorpPayType()) && !StringUtils.isEmpty(p.getSite()))
                .map(p -> {
                    GetOrgInfoResponseOld.OrgPayType temp = new GetOrgInfoResponseOld.OrgPayType();
                    temp.setCorpPayType(p.getCorpPayType());
                    temp.setSite(p.getSite());
                    List<String> payType = new ArrayList<>();
                    if (StringUtils.isNotBlank(p.getPaytype())) {
                        payType.addAll(Stream.of(p.getPaytype().split(",")).filter(pay -> !StringUtils.isEmpty(pay)).collect(Collectors.toList()));
                    }
                    temp.setPaytype(payType);
                    return temp;
                }).collect(Collectors.toList());
        // 对所有的 paytype 进行重新排序
        for (GetOrgInfoResponseOld.OrgPayType e : payTypeList) {
            e.getPaytype().sort(Comparator.reverseOrder());
        }

        Map<String, List<GetOrgInfoResponseOld.OrgPayType>> map = payTypeList.stream()
                .collect(Collectors.groupingBy(GetOrgInfoResponseOld.OrgPayType::getSite));
        GetSwitchListRequest request = new GetSwitchListRequest();
        MbOrgInfo topMbOrgInfo = getCompanyInfo(orgId);
        if (topMbOrgInfo == null){
            log.error("查询上级公司出错，orgId为{}", orgId);
            return Collections.emptyList();
        }
        request.setOrgId(topMbOrgInfo.getOrgId());
        GetAllSwitchResponse switchListResponse = getAllSwitchService.allSwitch(request.getOrgId(), request.getUId());
        Map<String, String> switchMap = switchListResponse.getSupplierCompanyValue();
        String topOrgId = topMbOrgInfo.getOrgId();
        //排序
        for (int i = 0; i < SiteEnum.values().length; i++) {
            String site = SiteEnum.values()[i].getCode();
            String value = switchMap.get(topOrgId.concat("_").concat(site));
            if (SiteEnum.values()[i].equals(SiteEnum.FLIGHTINTL)){
                // 国际机票需要另外处理,因为在SiteEnum中国际机票为flightintl而switchListResponse.getSupplierCompanyValue中使用的是intlflight
                value = switchMap.get(topOrgId.concat("_").concat("intlflight"));
            }
            if (!SiteEnum.values()[i].equals(SiteEnum.OTHER) && Objects.equals(value, ENABLE)){
                orgPayTypeList.addAll(Optional.ofNullable(map.get(site)).orElse(new ArrayList<>()));
            }
        }
        log.info("returnData:{}", JsonUtils.toJsonString(orgPayTypeList));
        return orgPayTypeList;
    }

    public boolean supplementSite(GetPayConfigRequest request, List<MbOrgPayType> payList){
        //补
        Set<String> setPayList = payList.stream().filter(p -> p != null && !StringUtils.isEmpty(p.getCorpPayType()) && !StringUtils.isEmpty(p.getSite()))
                .map(MbOrgPayType::getSite).collect(Collectors.toSet());
        List<MbOrgPayType> lists = Lists.newArrayList();
        for (SiteEnum siteEnum :SiteEnum.values()) {
            if (siteEnum == SiteEnum.OTHER){
                continue;
            }
            String code = siteEnum.getCode();
            if(!setPayList.contains(code)){
                //因公
                if (StringUtils.equals(OrgTypeEnum.D.getCode(), request.getType(), false)) {
                    lists.add(new MbOrgPayType(request.getOrgId(), CorpPayTypeEnum.PUB.toString(), null, code));
                }else {
                    lists.add(new MbOrgPayType(request.getOrgId(), CorpPayTypeEnum.PUB.toString(), PayTypeEnum.ACCNT.getType(), code));
                    //接送机/接送站 因公目前不需要因私
                    if (!siteEnum.getCode().equals(SiteEnum.TRAINTRANSFER.getCode()) && !siteEnum.getCode().equals(SiteEnum.AIRPORTTRANSFER.getCode())){
                        lists.add(new MbOrgPayType(request.getOrgId(), CorpPayTypeEnum.PUB.toString(), PayTypeEnum.PPAY.getType(), code));
                    }
                }
                //因私
                lists.add(new MbOrgPayType(request.getOrgId(), CorpPayTypeEnum.OWN.toString(), PayTypeEnum.PPAY.getType(), code));
            }
        }

        if(lists.size()>0){
            orgPayTypeService.batchSavePayType(lists);
            return true;
        }
        return false;
    }

    /**
     * 是否有父级组织,
     * 有父级组织->将父级组织的支付方式导入到子组织，return true
     * 无父级组织-> return false
     */
    public boolean hasParentOrganization(String orgId){
        MbOrgInfo mbOrgInfo = mbOrgInfoMapper.selectOneByOrgId(orgId);
        if (mbOrgInfo == null || StringUtils.isBlank(mbOrgInfo.getParentId())){
            return false;
        }
        List<MbOrgPayType> mbOrgPayTypeList = orgPayTypeService.findByOrdId(mbOrgInfo.getParentId());
        List<MbOrgPayType> newMbOrgPayTypeList = mbOrgPayTypeList.stream()
                .peek(payType -> {
                    payType.setOrgId(orgId);
                    payType.setIsDeleted(0);
                }).collect(Collectors.toList());
        log.info("mbOrgPayTypeList:{}", JsonUtils.toJsonString(newMbOrgPayTypeList));
        orgPayTypeService.batchSavePayType(newMbOrgPayTypeList);
        return true;

    }

    /**
     * 是否设置了支付和设置
     * 设置了->使用设置的支付设置，返回true
     * 未设置->流程往下走，返回false
     */
    public boolean hasPayConfig(List<OrgInitEvent.PayTypeConfigType> payTypeConfigList){
        return !CollectionUtils.isEmpty(payTypeConfigList);

    }

    /**
     * 获取上级第一个为公司的组织（不包含当前组织）
     */
    public MbOrgInfo getFirstCompanyInfo(String orgId) {
        if (StringUtils.isBlank(orgId)) {
            return null;
        }
        List<MbOrgInfo> infoList = mbOrgInfoMapper.listByOrgIds(Collections.singletonList(orgId));
        if (CollectionUtils.isNotEmpty(infoList)) {
            MbOrgInfo mbOrgInfo = infoList.get(0);
            if (StringUtils.isBlank(mbOrgInfo.getParentId())){
                return mbOrgInfo;
            } else {
                return getCompanyInfo(mbOrgInfo.getParentId());
            }
        }
        return null;
    }

    /**
     * 获取上级第一个为公司的组织（包含当前组织）
     */
    public MbOrgInfo getCompanyInfo(String orgId) {
        if (StringUtils.isBlank(orgId)) {
            return null;
        }
        List<MbOrgInfo> infoList = mbOrgInfoMapper.listByOrgIds(Collections.singletonList(orgId));
        if (CollectionUtils.isNotEmpty(infoList)) {
            MbOrgInfo mbOrgInfo = infoList.get(0);
            if (TYPE_COMPANY.equals(mbOrgInfo.getOrgType()) || StringUtils.isBlank(mbOrgInfo.getParentId())) {
                return mbOrgInfo;
            } else {
                return getCompanyInfo(mbOrgInfo.getParentId());
            }
        }
        return null;
    }



}
